package com.zerowidth.moc.web.controller.serviceimpl;

import com.zerowidth.db.bean.AppConfigBean;
import com.zerowidth.db.bean.NoticeBean;
import com.zerowidth.db.bean.VersionBean;
import com.zerowidth.db.op.AppConfigDB;
import com.zerowidth.db.op.NoticeDB;
import com.zerowidth.db.op.VersionDB;
import com.zerowidth.moc.web.controller.service.VersionService;
import com.zerowidth.moc.web.resp.ResCode;
import com.zerowidth.moc.web.resp.ResultBean;
import com.zerowidth.moc.web.resp.helper.ResponseCreator;
import com.zerowidth.moc.web.utils.CollectionUtils;
import com.zerowidth.moc.web.utils.LogUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class VersionServiceImpl implements VersionService {

    private static List<AppConfigBean> configBeanList = null;
    private static List<NoticeBean> noticeBeanList = null;

    @Override
    public ResponseEntity<ResultBean<VersionBean>> getLatestVersion(String appVersionName, String app_channel, String currentVersion) {
        List<VersionBean> versionBeanList = VersionDB.getNewVersionList(appVersionName, app_channel, currentVersion);

        if (CollectionUtils.isEmpty(versionBeanList)) {
            return ResponseCreator.creatOk(null, ResCode.CODE_OK, "已经是最新版本");
        }

        VersionBean latestVersion = CollectionUtils.get(versionBeanList, 0);
        return ResponseCreator.creatOk(latestVersion, ResCode.CODE_OK, "有新版本发布");
    }

    @Override
    public ResponseEntity<ResultBean<List<AppConfigBean>>> getAppConfigData(String app_channel, HttpServletRequest request, boolean force_update) {

        if (force_update) {
            //客户端要求强制刷新时，直接读取数据库
            LogUtil.e("从数据库中读取最新配置信息");
            configBeanList = AppConfigDB.getAppConfigData(app_channel, request);
        } else {
            //客户端没有强制刷新时，尝试读取内存缓存
            if (CollectionUtils.isEmpty(configBeanList)) {
                LogUtil.e("从数据库中读取最新配置信息");
                configBeanList = AppConfigDB.getAppConfigData(app_channel, request);
            }

        }

        return ResponseCreator.creatOk(configBeanList, ResCode.CODE_OK, "");
    }

    @Override
    public ResponseEntity<ResultBean<List<NoticeBean>>> getNoticeList(String versionName) {

        // 每次都重新读取
        //LogUtil.e("从数据库中读取最新通知信息");
        noticeBeanList = NoticeDB.getNoticeList(versionName);

        return ResponseCreator.creatOk(noticeBeanList, ResCode.CODE_OK, "");
    }

}
